package com.dao;

import com.model.Category;
import com.utils.DbUntil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CategoryDao {

    private Connection connection;

    //在这里初始化  这里获取链接
    public CategoryDao() {
        connection = DbUntil.getConnection();
    }

    //公有方法 获取所有种类信息
    public List<Category> getAllCategories() {
        List<Category> categories = new ArrayList<Category>();
        try {
            Statement statement = connection.createStatement();
            //这里是查询select * from category
            ResultSet rs = statement.executeQuery("select * from category");
            while (rs.next()) {
                Category category = new Category();
                category.setCategory_id(rs.getString("category_id"));
                category.setCategory_name(rs.getString("category_name"));
                category.setStatus(rs.getString("status"));
                categories.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return categories;
    }

    //通过类别id获取类别
    public List<Category> getCategoryByCategoryId(int categoryId){
        List<Category> categories = new ArrayList<Category>();
        try {
            Statement statement = connection.createStatement();
            String sql = "select * from category where category_id='"+categoryId+"'";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                Category category = new Category();
                category.setCategory_id(rs.getString("category_id"));
                category.setCategory_name(rs.getString("category_name"));
                category.setFather_id(rs.getString("father_id"));
                category.setStatus(rs.getString("status"));
                categories.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return categories;
    }

    //通过父类id获取类别
    public List<Category> getCategoryByFatherId(int categoryId){
        List<Category> categories = new ArrayList<Category>();
        try {
            Statement statement = connection.createStatement();
            String sql = "select * from category where father_id='"+categoryId+"'";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                Category category = new Category();
                category.setCategory_id(rs.getString("category_id"));
                category.setCategory_name(rs.getString("category_name"));
                category.setFather_id(rs.getString("father_id"));
                category.setStatus(rs.getString("status"));
                categories.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return categories;
    }
}
